<template>
  <el-dialog
      :model-value="visible"
      title="新增生产计划"
      width="700px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form ref="planFormRef" :model="planForm" :rules="rules" label-width="100px">
      <el-form-item label="任务单号" prop="pplanSheet">
        <el-input v-model="planForm.pplanSheet" placeholder="请输入唯一的生产任务单号" />
      </el-form-item>
      <el-divider content-position="left">计划条目</el-divider>
      <el-table :data="planForm.items" border style="width: 100%; margin-bottom: 20px;">
        <el-table-column label="产品" width="300">
          <template #default="scope">
            <el-form-item :prop="'items.' + scope.$index + '.pid'" :rules="rules.pid">
              <el-select v-model="scope.row.pid" placeholder="请选择产品" filterable style="width: 100%;">
                <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="`${item.name} (${item.id})`"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            <el-form-item :prop="'items.' + scope.$index + '.amount'" :rules="rules.amount">
              <el-input-number v-model="scope.row.amount" :min="1" controls-position="right" style="width: 100%;"/>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-button type="danger" :icon="Delete" circle @click="handleRemoveItem(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" plain @click="handleAddItem">添加条目</el-button>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch, defineProps, defineEmits} from 'vue'
import {Delete} from '@element-plus/icons-vue'
import {createPplan, getAllProducts} from '@/api/modules/pplan'
import {ElMessage} from 'element-plus'

const props = defineProps({
  visible: {type: Boolean, default: false}
})
const emit = defineEmits(['update:visible', 'success'])

const planFormRef = ref(null)
const productOptions = ref([])
const planForm = reactive({pplanSheet: '', items: []})
const rules = {
  pplanSheet: [{required: true, message: '请输入任务单号', trigger: 'blur'}],
  pid: [{required: true, message: '请选择产品', trigger: 'change'}],
  amount: [{required: true, message: '请输入数量', trigger: 'blur'}]
}

const fetchProductOptions = async () => {
  try {
    productOptions.value = await getAllProducts()
  } catch (error) {
    console.error('获取产品选项失败', error)
  }
}
const handleAddItem = () => {
  planForm.items.push({pid: '', amount: 1})
}
const handleRemoveItem = (index) => {
  planForm.items.splice(index, 1)
}

const handleSubmit = () => {
  planFormRef.value.validate(async (valid) => {
    if (valid) {
      if (planForm.items.length === 0) {
        ElMessage.warning('请至少添加一个计划条目');
        return;
      }
      try {
        await createPplan(planForm)
        ElMessage.success('生产计划创建成功')
        emit('success')
        handleClose()
      } catch (error) {
        console.error('创建失败', error)
      }
    }
  })
}

const handleClose = () => {
  if (planFormRef.value) planFormRef.value.resetFields()
  planForm.items = []
  emit('update:visible', false)
}

watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchProductOptions()
    if (planForm.items.length === 0) handleAddItem()
  }
})
</script>
